package gee

import (
	"html/template"
	"log"
	"net/http"
	"strings"
)

type Engine struct {
	*RouterGroup
	router        *Router
	groups        []*RouterGroup
	htmlTemplates *template.Template
	funcMap       template.FuncMap
}

type HandleFunc func(context *Context)
type H map[string]any

func New() *Engine {
	engine := &Engine{
		router: NewRouter(),
		groups: make([]*RouterGroup, 0),
	}
	engine.RouterGroup = &RouterGroup{
		engine: engine,
	}
	engine.groups = append(engine.groups, engine.RouterGroup)
	return engine
}

//默认使用Logger与Recover中间件
func Default() *Engine {
	engine := &Engine{
		router: NewRouter(),
		groups: make([]*RouterGroup, 0),
	}
	engine.RouterGroup = &RouterGroup{
		engine: engine,
	}
	//第一个路由组，也是根路由组，为""，里面的中间件作用于全局
	engine.groups = append(engine.groups, engine.RouterGroup)
	engine.middlewares = append(engine.middlewares, Logger(), Revcover())
	return engine
}

func (engine *Engine) GET(pattern string, handle HandleFunc) {
	engine.router.addRoute("GET", pattern, handle)
}

func (engine *Engine) POST(pattern string, handle HandleFunc) {
	engine.router.addRoute("POST", pattern, handle)
}

func (engine *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	context := NewContext(w, r)
	groups := engine.groups
	context.engine = engine
	for i := range groups {
		if strings.HasPrefix(context.Path, groups[i].prefix) {
			context.handles = append(context.handles, groups[i].middlewares...)
		}
	}
	engine.router.handles(context)
}

func (engine *Engine) Run(addr string) {
	log.Fatal(http.ListenAndServe(addr, engine))
}

func (e *Engine) SetFuncMap(funcmap template.FuncMap) {
	e.funcMap = funcmap
}

func (e *Engine) LoadHTMLGlob(partten string) {
	e.htmlTemplates = template.Must(template.New("").Funcs(e.funcMap).ParseGlob(partten))
}
